package asia.yuanding.wechat.web.service.impl;

import asia.yuanding.wechat.web.entity.SessionList;
import asia.yuanding.wechat.web.entity.User;
import asia.yuanding.wechat.web.service.SessionListService;
import asia.yuanding.wechat.web.service.UserService;
import cn.hutool.system.UserInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import asia.yuanding.wechat.web.entity.SessionInfo;
import asia.yuanding.wechat.web.service.SessionInfoService;
import asia.yuanding.wechat.web.mapper.SessionInfoMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author YuanDing
* @description 针对表【session_info】的数据库操作Service实现
* @createDate 2025-08-03 23:01:18
*/
@Service
public class SessionInfoServiceImpl extends ServiceImpl<SessionInfoMapper, SessionInfo>
    implements SessionInfoService{

    @Resource
    private SessionListService sessionListService;

    @Resource
    private UserService userService;

    @Async
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveMessageAsync(SessionInfo sessionInfo , String contactId) {
        sessionInfo.setStatus(1);
        sessionInfo.setType(1);
        // 先保存一下发送人的
        this.save(sessionInfo);

        // 再保存一下接收人的

        // 此处更新一下接收人的消息列表

//        List<String> sessionIds = sessionListService.lambdaQuery()
//                .eq(SessionList::getSessionId, sessionInfo.getSessionId())
//                .list().stream().map(SessionList::getSessionId)
//                .collect(Collectors.toList());

        SessionList sessionList = new SessionList();

        sessionList.setIsShow(1);
        sessionList.setUpdateTime(sessionInfo.getCreateTime());
        sessionList.setLastTime(sessionInfo.getCreateTime());


        String uId = sessionInfo.getCreateUser();

        User user = userService.lambdaQuery()
                .eq(User::getUid, uId)
                .one();

        sessionList.setLastAvatar(user.getAvatar());
        sessionList.setLastName(user.getNickname());
        sessionList.setContactId(user.getUid());
        sessionList.setContactName(user.getNickname());
        sessionList.setLastMessage(sessionInfo.getContent());

        sessionListService.lambdaUpdate()
                        .eq(SessionList::getSessionId, sessionInfo.getSessionId())
                                .update(sessionList);




        sessionInfo.setId(null);
        sessionInfo.setType(2);
        sessionInfo.setCreateUser(contactId);
        this.save(sessionInfo);
    }
}




